using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Serialization;

public class Character : MonoBehaviour
{
    public static Character instance;
    private float speed = 3;
    [FormerlySerializedAs("isPicking")] public bool isPicked = false;
    private Animator animator;
    private SpriteRenderer spriterenderer;
    private CordRear attachCord;
    public GameObject attachCenter;


    public List<CordRear> cordRears;//所有已检测到绳子

    private void Awake()
    {
        instance = this;
        cordRears = new List<CordRear>();

    }

    void Start()
    {
        animator = GetComponent<Animator>();
        spriterenderer = GetComponent<SpriteRenderer>();
        // attachCord = Ropes[0];
        // attachCenter = attachCord.GetComponent<CordChildren>().controlAnchors.GetFirstGameObj();
    }

    // Update is called once per frame
    void Update()
    {
        MasterMove();
        Attach();
    }
    public void MasterMove()
    {
        // 检查上方向键是否按下
        if (Input.GetKey(KeyCode.W))
        {
            this.gameObject.transform.Translate(Vector3.up * Time.deltaTime * speed);
        }

        // 检查下方向键是否按下
        if (Input.GetKey(KeyCode.S))
        {
            this.gameObject.transform.Translate(Vector3.down * Time.deltaTime * speed);
        }

        // 检查左方向键是否按下
        if (Input.GetKey(KeyCode.A))
        {
            this.gameObject.transform.Translate(Vector3.left * Time.deltaTime * speed);
            spriterenderer.flipX = true;
        }

        // 检查右方向键是否按下
        if (Input.GetKey(KeyCode.D))
        {
            this.gameObject.transform.Translate(Vector3.right * Time.deltaTime * speed);
            spriterenderer.flipX = false;
        }

        // 按E拾取最先接触的线
        if(Input.GetKey(KeyCode.E))
        {
            if(cordRears.Count != 0 && !isPicked)
            {
                isPicked = true;
                attachCord = cordRears[0];
                attachCenter = attachCord.GetComponent<CordChildren>().controlAnchors.GetFirstGameObj();
            }
        }

        // 根据按键状态设置动画状态
        if (Input.GetKey(KeyCode.W) || Input.GetKey(KeyCode.S) || Input.GetKey(KeyCode.A) || Input.GetKey(KeyCode.D))
        {
            animator.SetBool("IsRun", true);
        }
        else
        {
            animator.SetBool("IsRun", false);
        }
    }

    public void Attach()
    {
        if (isPicked && !attachCord.isConnected)
        {
            //Debug.Log(Vector2.Distance(attachCenter.transform.position, transform.position));
            if (Vector3.Distance(attachCenter.transform.position, transform.position) > attachCord.length)
            {
                isPicked = false;
                return;
            }
            attachCord.transform.position = transform.position;
        }
    }
}
